//
//  KWNQuestionListViewController.m
//  KWNClient
//
//  Created by 张明磊 on 14/10/22.
//  Copyright (c) 2014年 张明磊. All rights reserved.
//

#import "KWLMyListViewController.h"
#import "KWLQDetailViewController.h"
#import "KWNNetwork.h"
#import "Model_myList.h"
#import "KWLMyQDetailViewController.h"
#import "Model_user.h"
#import "KWLLoginViewController.h"
//上拉加载更多
#import "MJRefresh.h"
#import "KFLMyListRequest.h"
#import "KFWMessageViewController.h"
#import "RESideMenu.h"

@interface KWLMyListViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) NSMutableArray *array_data;
@property (weak, nonatomic) UIView *imageView_title;
@property (strong, nonatomic) UITableView *tab_mylistTab;
@property (strong, nonatomic) UIImageView *imageview_noData;
@property (strong, nonatomic) NSArray *array_location;

/**
 下拉刷新
 **/
@property (assign, nonatomic) BOOL reloading;
@property NSInteger myListStartNum;
@end

@implementation KWLMyListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _myListStartNum = 0;
    _array_data = [[NSMutableArray alloc] init];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *array_tmp = @[
                               @"北京",@"上海",@"天津",@"重庆",@"黑龙江省",@"吉林省",@"辽宁省",@"河北省",@"山西省",@"内蒙古",@"山东省",@"安徽省",@"江苏省",@"浙江省",@"江西省",@"福建省",@"河南省",@"湖北省",@"湖南省",@"广东省",@"广西",@"海南省",@"四川省",@"贵州省",@"云南省",@"西藏",@"陕西省",@"甘肃省",@"青海省",@"宁夏",@"新疆",@"香港",@"澳门",@"台湾省"];
        dispatch_async(dispatch_get_main_queue(), ^{
            _array_location = array_tmp;
        });
    });

    [self UI_qTitle];
    
    _imageview_noData = [[UIImageView alloc] initWithFrame:CGRectMake((MainScreenWidth - 131)/2, (MainScreenHeight - self.imageView_title.frame.origin.y - self.imageView_title.frame.size.height - 222 - 44)/2 + self.imageView_title.frame.origin.y + self.imageView_title.frame.size.height, 131, 222)];
    _imageview_noData.image = [UIImage imageFileName:@"noMylistData.png"];
    [self.view addSubview:_imageview_noData];
    _imageview_noData.hidden = YES;

    [self UI_qList];
    //[self getData_questionList];
}

- (void)dealloc
{
    _imageView_title = nil;
    _tab_mylistTab = nil;
    _array_location = nil;
    _array_data = nil;
    _imageview_noData = nil;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //[self data_myList];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    _myListStartNum = 0;
    [self getMyListData];
}


#pragma mark - 刷新数据 -

//新版本获取列表数据
- (void)getMyListData
{
    [SVProgressHUD showWithStatus:@"加载中..."];
    
    KFLMyListRequest *request = [[KFLMyListRequest alloc] initRequest];
    request.myList_startNum = [NSString stringWithFormat:@"%ld",(long)_myListStartNum];
    request.myList_displaynum = [NSString stringWithFormat:@"%d",kCountOfPage];
    
    __weak KWLMyListViewController *aself = self;
    [request startToRequestWithBlock:^(NSInteger stateCode, NSMutableArray *result) {
        
        [aself.tab_mylistTab headerEndRefreshing];
        [aself.tab_mylistTab footerEndRefreshing];

        switch (stateCode) {
            case 10000:
            {
                [SVProgressHUD dismiss];
                if (aself.myListStartNum == 0) {
                    [aself.array_data removeAllObjects];
                }
                
                [aself.array_data addObjectsFromArray:result];
                
                if (aself.array_data.count == 0) {
                    aself.imageview_noData.hidden = NO;
                    aself.tab_mylistTab.hidden = NO;
                }
                else
                {
                    aself.imageview_noData.hidden = YES;
                    aself.tab_mylistTab.hidden = NO;
                    aself.myListStartNum = _myListStartNum + kCountOfPage;
                    [aself.tab_mylistTab reloadData];
                }
                
            }
                break;
            case 10003:
            {
                [SVProgressHUD dismiss];
                [aself myListTokenIsFailure];
            }
                break;
            case 10009:
            {
                NSString *string_msg  = result[0];
                [SVProgressHUD dismissWithSuccess:string_msg afterDelay:1.5];
                if (aself.array_data.count == 0) {
                    aself.imageview_noData.hidden = NO;
                    aself.tab_mylistTab.hidden = NO;
                }
                else
                {
                    aself.imageview_noData.hidden = YES;
                    aself.tab_mylistTab.hidden = NO;
                }
            }
                break;
            default:
            {
                NSString *string_msg  = result[0];
                [SVProgressHUD dismissWithError:string_msg afterDelay:1.5];
                
                if (aself.array_data.count == 0) {
                    aself.imageview_noData.hidden = NO;
                    aself.tab_mylistTab.hidden = NO;
                }
            }
                break;
        }
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)UI_qTitle{
//    self.view.backgroundColor = RGB(239, 239, 244);
    
    UIView *imageView_title = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44 + IOS7_SIZE)];
    imageView_title.backgroundColor = RGB(91, 165, 229);
    [self.view addSubview:imageView_title];
    _imageView_title = imageView_title;
    
    UIButton *button_menu = [UIButton buttonWithType:UIButtonTypeCustom];
    button_menu.frame = CGRectMake(0, IOS7_SIZE, 60, 45);
    [button_menu setImage:[UIImage imageFileName:@"btn_leftList.png"] forState:UIControlStateNormal];
    //button_menu.tag = KWNDetailViewButtonTag_back;
    [button_menu addTarget:self action:@selector(didClickButton_questionList:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button_menu];
    
    UILabel *label_title = [[UILabel alloc] initWithFrame:CGRectMake(imageView_title.frame.origin.x,IOS7_SIZE + 5,imageView_title.frame.size.width,35)];
    label_title.backgroundColor = [UIColor clearColor];
    label_title.textColor = ColorOfTitle;
    label_title.textAlignment = NSTextAlignmentCenter;
    label_title.font = [UIFont fontWithName:@"Helvetica-Bold" size:16.0f];
    [self.view addSubview:label_title];
    label_title.text = @"我的回答";
}

- (void)UI_qList{
    if (!_tab_mylistTab) {
         _tab_mylistTab = [[UITableView alloc] initWithFrame:CGRectMake(_imageView_title.frame.origin.x, _imageView_title.frame.origin.y + _imageView_title.frame.size.height, _imageView_title.frame.size.width, self.view.frame.size.height - _imageView_title.frame.size.height)];
//        _tab_mylistTab.backgroundColor = RGB(239, 239, 244);
        _tab_mylistTab.backgroundColor = [UIColor clearColor];
        _tab_mylistTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tab_mylistTab.delegate = self;
        _tab_mylistTab.dataSource = self;
        _tab_mylistTab.tag = 100;
        [self.view addSubview:_tab_mylistTab];
        
        __weak KWLMyListViewController *aself = self;
        
        //下拉刷新
        [_tab_mylistTab addHeaderWithCallback:^{
            aself.myListStartNum = 0;
            [aself getMyListData];
        }];

        //加入上拉加载更多
        [_tab_mylistTab addFooterWithCallback:^{
            [aself getMyListData];
        }];
        
    }
}

- (void)didClickButton_questionList:(UIButton *)button{
    
    [[RESideMenu sharedInstance] presentMenuViewController];
    [MobClick event:@"caidan"];
}



#pragma mark - 账号被替换下线提示 -
- (void)myListTokenIsFailure{
    UIAlertView *alter_login;
    if(IOS8_VERSION){
        alter_login = [[UIAlertView alloc] initWithTitle:@"您的来问律师账号已在其它地方登录，请您重新登录此设备。如果不是您的操作，您的密码可能已泄露，请及时更改密码，或联系快问律师客服邮箱laiwenlvshi@kuaifawu.com。" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    }
    else{
        alter_login = [[UIAlertView alloc] initWithTitle:nil message:@"您的来问律师账号已在其它地方登录，请您重新登录此设备。如果不是您的操作，您的密码可能已泄露，请及时更改密码，或联系快问律师客服邮箱laiwenlvshi@kuaifawu.com。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    }
    alter_login.tag = 10003;
    [alter_login show];
}

#pragma mark - alertView -
/**
 *  账号被替换下线
 */
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (alertView.tag) {
            //账号替换
        case 10003:{
            KWLLoginViewController *login = [[KWLLoginViewController alloc] initWithTag:6];
            [self pushViewController:login];
        }break;
        default:
            break;
    }
}

#pragma mark - UITableViewDelegate -

/**
 *  列表数据源
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _array_data.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"My_List";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle: 	UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIImageView *imageviw_wen = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
        imageviw_wen.image = [UIImage imageFileName:@"wen.png"];
        
        UIImageView *imageview_ren = [[UIImageView alloc] initWithFrame:CGRectMake(imageviw_wen.frame.origin.x + imageviw_wen.frame.size.width + 3, 13, 11, 15)];
        imageview_ren.image = [UIImage imageFileName:@"image_free_Person.png"];
        
        UILabel *label_name = [UIUtils creatLabel];
        label_name.frame = CGRectMake(imageview_ren.frame.origin.x + imageview_ren.frame.size.width + 3, 13, 80, 15);
        label_name.font = FontOfHelveticaBold(13);
        label_name.textColor = RGB(206, 206, 206);
        label_name.tag = TagOfView + 1;
        
        UIImageView *imageview_message = [[UIImageView alloc] initWithFrame:CGRectMake(MainScreenWidth - 143, 10, 20, 19)];
        imageview_message.image = [UIImage imageFileName:@"image_qListType.png"];
        
        UILabel *label_QuestionType = [UIUtils creatLabel];
        label_QuestionType.frame = CGRectMake(MainScreenWidth - 120, 13, 52, 15);
        label_QuestionType.textColor = RGB(134, 177, 217);
        label_QuestionType.font = FontOfHelveticaBold(13);;
        label_QuestionType.tag = TagOfView + 2;
        
        UILabel *label_QuestionDetailType = [UIUtils creatLabel];
        label_QuestionDetailType.frame = CGRectMake(MainScreenWidth - 62, 13, 52, 15);
        label_QuestionDetailType.textColor = RGB(134, 177, 217);
        label_QuestionDetailType.font = FontOfHelveticaBold(13);
        label_QuestionDetailType.tag = TagOfView + 3;
        
        UILabel *label_text = [UIUtils creatLabel];
        [label_text sizeToFit];
        label_text.numberOfLines = 0;
        label_text.font = FontOfQuestionList;
        label_text.frame = CGRectMake(10, 40, MainScreenWidth - 20, 16);
        label_text.textColor = ColorOfQuestionList;
        label_text.tag = TagOfView + 4;
        
        UILabel *label_solve = [UIUtils creatLabel];
        label_solve.font = FontOfSystem(13);
        label_solve.frame = CGRectZero;
        label_solve.textColor = RGB(194, 194, 194);
        label_solve.tag = TagOfView + 7;

        UILabel *label_time = [UIUtils creatLabel];
        label_time.font = FontOfSystem(13);
        label_time.frame = CGRectZero;
        label_time.textColor = RGB(194, 194, 194);
        label_time.tag = TagOfView + 5;
        
        UIImageView *imageview_line = [[UIImageView alloc] initWithFrame:CGRectZero];
        imageview_line.tag = TagOfView + 6;
        
        [cell addSubview:imageviw_wen];
        [cell addSubview:imageview_ren];
        [cell addSubview:imageview_message];
        [cell addSubview:label_QuestionType];
        [cell addSubview:label_name];
        [cell addSubview:label_QuestionDetailType];
        [cell addSubview:label_text];
        [cell addSubview:label_solve];
        [cell addSubview:label_time];
        [cell addSubview:imageview_line];
    }
    [self installListCell:cell withIndex:indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    Model_myList *list = _array_data[indexPath.row];
    return list.myList_height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Model_myList *list = _array_data[indexPath.row];
    KFWMessageViewController *controller = [[KFWMessageViewController alloc] initWithQID:list.string_id andUpdataUnread:YES];
    [self pushViewController:controller];
}

#pragma mark - 复用tableView -
/**
 *  复用tableView
 */
- (void)installListCell:(UITableViewCell *)cell withIndex:(NSInteger)index{
    
    UILabel *label_name = (UILabel *)[cell viewWithTag:TagOfView + 1];
    UILabel *label_QuestionType = (UILabel *)[cell viewWithTag:TagOfView + 2];
    UILabel *label_QuestionDetailType = (UILabel *)[cell viewWithTag:TagOfView + 3];
    UILabel *label_text = (UILabel *)[cell viewWithTag:TagOfView + 4];
    UILabel *label_solve = (UILabel *)[cell viewWithTag:TagOfView + 7];
    UILabel *label_time = (UILabel *)[cell viewWithTag:TagOfView + 5];
    UIImageView *imageview_line = (UIImageView *)[cell viewWithTag:TagOfView + 6];
    
    Model_myList *list = _array_data[index];
    NSInteger kind_area = list.string_area.integerValue;
    label_name.text = [NSString stringWithFormat:@"%@网友",_array_location[kind_area]];
    
    NSInteger kind = list.string_kind.integerValue;
    NSArray *arr = [UIUtils getQuestionTypeWithkind:kind];
    label_QuestionType.text = arr[0];
    label_QuestionDetailType.text = arr[1];

    label_text.text = list.string_content;
    CGFloat height = [UIUtils heightFor:label_text.text withFont:FontOfQuestionList labWidth:MainScreenWidth-20];
    if (height >= 40) {
        height = 40;
    }
    else
    {
        height = 20;
    }
    label_text.frame = CGRectMake(10, 40, MainScreenWidth - 20, height);
    
    switch ([list.string_isSolve integerValue]) {
        case 0:{
            label_solve.text = [NSString stringWithFormat:@"待评价"];
            label_solve.textColor = RGB(240, 139, 93);
        }break;
        case 1:
        {
            label_solve.text = [NSString stringWithFormat:@"已解决"];
            label_solve.textColor = RGB(91, 157, 228);
        }break;
        default:
            break;
    }
    label_solve.frame = CGRectMake(10, label_text.frame.origin.y + label_text.frame.size.height + 10, 40, 15);
    label_time.text = list.string_time;
    label_time.frame = CGRectMake(label_solve.frame.origin.x + label_solve.frame.size.width + 5, label_text.frame.origin.y + label_text.frame.size.height + 10, 200, 15);

    imageview_line.frame = CGRectMake(0, label_time.frame.origin.y + label_time.frame.size.height + 9, MainScreenWidth, 1);
    imageview_line.backgroundColor = RGB(220, 220, 220);

//    if ([list.string_unRead intValue]>0) {
//        unreadview.hidden = NO;
//    }
//    else
//    {
//        unreadview.hidden = YES;
//    }
    
    label_time.text = [NSString stringWithFormat:@"%@",list.string_time];
}

- (void)didClickButton_content:(UIButton *)button{
    UITableViewCell *cell = [self reciveSuperViewCellWithView:button];
    UITableView *tableView = [self reciveSuperViewTableWithView:cell];
    NSIndexPath *index = [tableView indexPathForCell:cell];
    
    Model_myList *list = _array_data[index.row];
    NSString *string_count = [[Model_user sharedInstance] getUnReadCount];
    NSString *string_now = list.string_unRead;
    NSInteger int_count = string_count.integerValue - string_now.integerValue;
    [[Model_user sharedInstance] setUnReadCount:[NSString stringWithFormat:@"%ld",(long)int_count]];
    list.string_unRead = @"0";
    UIView *unreadview = (UIView *)[cell viewWithTag:14];
    unreadview.hidden = YES;
    
    KWLMyQDetailViewController *controller_myDetail = [[KWLMyQDetailViewController alloc] initWithID:list.string_id andTag:list.string_isSolve];
    [self pushViewController:controller_myDetail];
    //Model_questionList *model_list = _array_data[index.row];
    //KWNQDetailViewController *detail = [[KWNQDetailViewController alloc] initWithID:model_list.string_id];
    //[self pushViewController:detail];
}

#pragma mark - 获取上级控件 -
/**
 *  获取上级控件
 */
- (UITableViewCell *)reciveSuperViewCellWithView:(UIView *)view{
    for (UIView *next = [view superview]; next; next = next.superview){
        UIResponder *nextResponder;
        nextResponder = [view superview];
        if(IOS8_VERSION || IOS6_VERSION){
            nextResponder = [view superview];
        }
        else{
            nextResponder = [next nextResponder];
        }
        if ([nextResponder isKindOfClass:[UITableViewCell class]]){
            return (UITableViewCell *)nextResponder;
        }
    }
    return nil;
}

- (UITableView *)reciveSuperViewTableWithView:(UIView *)view{
    for (UIView *next = [view superview]; next; next = next.superview){
        UIResponder *nextResponder;
        if(IOS6_VERSION){
            nextResponder = [view superview];
        }
        else{
            nextResponder = [next nextResponder];
        }
        if ([nextResponder isKindOfClass:[UITableView class]]){
            return (UITableView *)nextResponder;
        }
    }
    return nil;
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    [scrollView didScrollViewToScroll];
//}


@end
